import 'package:flutter/material.dart';

class MSValueListenableBuilderDemo extends StatefulWidget {
  const MSValueListenableBuilderDemo({Key? key}) : super(key: key);

  @override
  State<MSValueListenableBuilderDemo> createState() =>
      _MSValueListenableBuilderDemoState();
}

class _MSValueListenableBuilderDemoState
    extends State<MSValueListenableBuilderDemo> {
  // 定义一个ValueNotifier，当数字变化时会通知 ValueListenableBuilder
  final ValueNotifier<int> _counter = ValueNotifier<int>(0);
  @override
  Widget build(BuildContext context) {
    // 点击 + 按钮不会触发整个 ValueListenableRoute 组件的 build
    print('build');
    return Scaffold(
      appBar: AppBar(title: const Text("ValueListenableBuilderDemo")),
      body: Center(
        child: ValueListenableBuilder<int>(
          valueListenable: _counter,
          builder: (ctx, value, child) {
            print('build-----ValueListenableBuilder');
            return Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                child!,
                Text("$value 次"),
              ],
            );
          },
          child: const Text("点击了"),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          // 点击后值 +1，触发 ValueListenableBuilder 重新构建
          _counter.value++;
        },
      ),
    );
  }

  void test() {
    ValueNotifier<double> notifier = ValueNotifier<double>(2.0);
    //添加监听者
    listener() {
      print('---> ${notifier.value}');
    }

    notifier.addListener(listener);
    //改编值后 监听者可以收到数据
    notifier.value = 3.0;
  }
}

class Counter extends ChangeNotifier {
  int _count = 0;
  int get count => _count;

  addCount() {
    _count++;
    notifyListeners();
  }
}

Counter _counter = Counter();

class ChangeNotifierTest extends StatefulWidget {
  const ChangeNotifierTest({super.key});

  @override
  _ChangeNotifierTestState createState() => _ChangeNotifierTestState();
}

class _ChangeNotifierTestState extends State<ChangeNotifierTest> {
  @override
  void initState() {
    super.initState();
    _counter.addListener(() {
      //add listener
      print('new count is :${_counter.count}');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _counter.dispose(); //remove listener
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ChangeNotifier test',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('ChangeNotifier test bar'),
        ),
        body: Center(
          child: Container(
            child: TextButton(
                onPressed: () {
                  _counter.addCount();
                },
                child: const Text('count')),
          ),
        ),
      ),
    );
  }
}
